import React, {useState} from 'react'
import {Button, Upload, Row, Col, message, Modal} from 'antd'
import type {RcFile, UploadFile} from 'antd/es/upload'
import {PlusOutlined} from '@ant-design/icons'
import styles from './index.less'
import {batchImg} from '@/service/carMessage/licence'
import {carNoPattern} from '@/utils/common/validator'

type PropsType = {
	title?: string // 弹框标题
	isModalOpen: boolean // 弹框是否可见
	accept?: any
	moreNum?: number
	setIsModalOpen: React.Dispatch<React.SetStateAction<boolean>>
	resetList: () => void // 导入保存方法
	uploadFileUrl?: string // 上传模板url
	fileData?: any
	fileNmae?: string
}

const getBase64 = (file: RcFile): Promise<string> =>
	new Promise((resolve, reject) => {
		const reader = new FileReader()
		reader.readAsDataURL(file)
		reader.onload = () => resolve(reader.result as string)
		reader.onerror = (error) => reject(error)
	})

const uploadButton = (
	<div>
		<PlusOutlined />
	</div>
)
const batchUpload = (props: PropsType) => {
	const {
		title = '批量导入车辆图片',
		isModalOpen,
		accept,
		moreNum = 50,
		setIsModalOpen,
		resetList,
		uploadFileUrl,
		fileData,
		fileNmae,
	} = props
	const [previewOpen, setPreviewOpen] = useState(false)
	const [previewImage, setPreviewImage] = useState('')
	const [previewTitle, setPreviewTitle] = useState('')
	const [fileList, setFileList] = useState<UploadFile[]>([])

	const handleCancel = () => setPreviewOpen(false)
	const uploadProps = {
		action: uploadFileUrl,
		name: fileNmae,
		data: (file: any) => {
			const nameRules = file?.name.split('.')
			const positionReg = [
				{targetAttr: 2, name: '行驶证正'},
				{targetAttr: 3, name: '行驶证副'},
				{targetAttr: 12, name: '网约车证'},
			]
			const targetAttr = positionReg?.filter(
				(item: any) => item?.name === nameRules[1],
			)[0]?.targetAttr
			return {...fileData, targetAttr}
		},
		fileList,
		beforeUpload: (file: any) => {
			const nameRules = file?.name.split('.')
			const isJpgOrPng = accept.includes(file?.type)
			if (!isJpgOrPng) {
				message.error('你只能上传JPG/PNG文件')
			}
			const isLt2M = file.size / 1024 / 1024 < 200
			if (!isLt2M) {
				message.error('文件大小不能大于200M')
			}
			const carReg = carNoPattern
			const carRule = carReg.test(nameRules[0])
			if (!carRule) {
				/* 进行验证 */
				message.error('车牌号不正确')
				return false
			}
			const positionReg = ['行驶证正', '行驶证副', '网约车证']
			const positionRule = positionReg.includes(nameRules[1])
			if (!positionRule) {
				/* 进行验证 */
				message.error('文件名称中位置不正确')
				return false
			}
			const numberRule = fileList?.length <= 50
			if (!numberRule && fileList) {
				/* 进行验证 */
				message.error('最多上传50张图片')
				return false
			}
			const removalRule = fileList?.filter((item: {name: string}) => {
				const itemNameRules = item?.name.split('.')
				return (
					itemNameRules[0] === nameRules[0] &&
					itemNameRules[1] === nameRules[1]
				)
			})
			const flag = removalRule?.length === 0
			if (!flag) {
				/* 进行验证 */
				message.error(`${file?.name}图片重复,请删除再上传`)
				return false
			}
			return (
				isJpgOrPng &&
				isLt2M &&
				carRule &&
				positionRule &&
				numberRule &&
				flag
			)
		},
		onChange(info: any) {
			if (info.file.status === 'uploading') {
				setFileList(() => info?.fileList)
			}
			if (info.file.status === 'done') {
				message.success('上传成功')
				setFileList(() => info?.fileList)
			}
			if (info.file.status === 'error') {
				message.error(info?.file?.response.msg)
			}
		},
		async onPreview(file: UploadFile) {
			const url = file?.response?.data?.giftNamespace
			if (!url && !file.preview) {
				// eslint-disable-next-line no-param-reassign
				file.preview = await getBase64(file.originFileObj as RcFile)
			}
			setPreviewImage(url || (file.preview as string))
			setPreviewOpen(true)
			setPreviewTitle(
				file.name || url!.substring(url!.lastIndexOf('/') + 1),
			)
		},
		onDrop() {},
		onRemove(info: any) {
			const list = info?.flist?.filter(
				(item: any) =>
					item.uid.toString() !== info?.file?.uid.toString(),
			)
			setFileList(() => list)
			message.success(`${info?.name}移除成功`)
		},
	}

	// 批量处理提交
	const onBatchSubmit = async () => {
		const positionReg = [
			{key: '0', label: '网约车证', value: '1'},
			{key: '1', label: '行驶证正', value: '2'},
			{key: '2', label: '行驶证副', value: '2'},
		]
		const fileLists = fileList.map((item: any) => {
			const arr = item?.response?.data?.filename?.split('.')
			const it = positionReg?.filter(
				(positionItem: {key: string; label: string}) =>
					positionItem?.label === arr[1],
			)[0]
			return {
				carPlateNo: arr[0],
				photoType: it.value,
				photoKey: item?.response?.data?.id,
				position: it.key,
			}
		})
		batchImg(fileLists)
			.then((res) => {
				if (res?.success) {
					message.success(res.msg)
					setIsModalOpen(false)
					resetList()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}
	return (
		<Modal
			title={title}
			open={isModalOpen}
			width={700}
			destroyOnClose
			onCancel={() => {
				setFileList(() => [])
				setIsModalOpen(false)
			}}
			footer={
				<>
					<Button
						onClick={() => {
							setFileList(() => [])
							setIsModalOpen(false)
						}}>
						取消
					</Button>
					<Button type="primary" size="small" onClick={onBatchSubmit}>
						保存
					</Button>
				</>
			}>
			<div className={styles.batchUpload}>
				<Row gutter={12}>
					<Col sm={{span: 24}}>
						<div className="tip">
							<div>图片上传格式和要求</div>
							<div>
								例如（陕A00001.行驶证正.png）（陕A00001.行驶证副.png）（陕A00001.网约车证.png）
							</div>
						</div>
					</Col>
					<Col sm={{span: 24}}>
						<div className="more">单次最多50张</div>
						<Upload {...uploadProps} listType="picture-card">
							{fileList?.length >= moreNum ? null : uploadButton}
						</Upload>
						<Modal
							open={previewOpen}
							title={previewTitle}
							footer={null}
							onCancel={handleCancel}>
							<img
								alt="example"
								style={{width: '100%'}}
								src={previewImage}
							/>
						</Modal>
					</Col>
				</Row>
			</div>
		</Modal>
	)
}
export default batchUpload
